<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>购物车</title>
    <base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
    <link type="text/css" rel="stylesheet" href="static/css/style.css">
</head>
<body>

<div id="header">
    <img class="logo_img" alt="" src="static/img/logo.gif" width="230px" height="80px">
    <span class="wel_word">购物车</span>
    <div>
        <span>欢迎<span class="um_span">${sessionScope.user.username}</span>光临网上书城</span>
        <a href="pages/order/order.jsp">我的订单</a>
        <a href="index.jsp">注销</a>&nbsp;&nbsp;
        <a href="index.jsp">返回</a>
    </div>
</div>

<div id="main">

    <table>
        <tr>
            <td>全选<input id="selectAll" type="checkbox" ></td>
            <td>购物车id</td>
            <td>商品名称</td>
            <td>数量</td>
            <td>单价</td>
            <td>金额</td>
            <td>操作</td>
        </tr>
    </table>
    <br/>
</div>
<div class="cart_info">
    <span class="cart_span">购物车中共有<span class="b_count">0</span>件商品</span>
    <span class="cart_span">总金额<span class="b_price">0.00</span>元</span>
    <span class="cart_span"><a href="javascript:void(0)" id="clearCart">清空购物车</a></span>
    <span class="cart_span"><a href="javascript:void(0)" id="checkout">去结账</a></span>
</div>

<div id="bottom">
		<span>
			网上书城.Copyright &copy;2020
		</span>
</div>
</body>
</html>
<script src="static/script/jquery-1.7.2.js"></script>
<script src="static/layui/layui.js"></script>
<script>
    var peipage;

    var myCheckTotalPrice = 0.0;

    $(function () {
        mypage()

        //计算总金额
        $("table :checkbox:gt(0)").live("change",function (){
            var value = $(this).parents("tr").find("td").eq(5).html();
            if(this.checked){
                myCheckTotalPrice += parseFloat(value);
            }else{
                myCheckTotalPrice -= parseFloat(value);
            }
            $("span.b_price").html(myCheckTotalPrice.toFixed(2))
            $("span.b_count").html($("table :checkbox:gt(0):checked").length);

        })

        //给td中的+ 与 - a连接添加事件
        $("table td.peitd").find("a").live("click" , function(){
            if(this.innerHTML == "+"){
                var span = $(this).next("span");
                span.html( parseInt(span.html()) + 1 )
                ///////////////////////正在写的代码////////////////////////////////
                if( $(this).parents("tr").find("input").prop("checked") ){
                    myCheckTotalPrice = myCheckTotalPrice + parseFloat($(this).parent().next().html());
                    $("span.b_price").html( myCheckTotalPrice.toFixed(2))
                }
            }else{
                var span = $(this).prev("span");
                if(parseInt(span.html()) > 1) {
                    span.html(parseInt(span.html()) - 1)
                    if( $(this).parents("tr").find("input").prop("checked") ) {
                        myCheckTotalPrice = myCheckTotalPrice - parseFloat($(this).parent().next().html());
                        $("span.b_price").html(myCheckTotalPrice.toFixed(2))
                    }
                }
            }
            var priceTd = $(this).parent().next();//单价td
            var totalPriceTd =  $(this).parent().next().next();//总价的td
            var val = (parseInt(span.html()) * parseFloat(priceTd.html())).toFixed(2);//算出新的总价金额
            totalPriceTd.html(val)//将新的总价金额赋值给到总价的td中

            var idtd = totalPriceTd.parent().find("td").eq(1);
            $.post("CartServlet","method=updateCountTotalPrice&count="+span.html()+"&totalPrice="+totalPriceTd.html()+"&id="+idtd.html(),function(msg){

            })
        })

        //结算
        $("#checkout").click(function (){
            var ids = "" ;
            $("table :checkbox:gt(0):checked").each(function(){
                ids += this.value+",";
            })
            if(ids == ""){
                layer.msg("此少勾选一项", {
                    icon: 2,
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                });
            }else{
                window.location.href = "OrderServlet?method=createOrder&ids="+ids;
            }
        });

        //全选/全不选
        $("#selectAll").change(function(){
            $("table :checkbox").prop("checked" , this.checked);
            myCheckTotalPrice = 0.0
            if( $("table :checkbox").prop("checked")){
                $("table :checkbox:gt(0)").each(function(){
                    var value = $(this).parents("tr").find("td").eq(5).html();
                    myCheckTotalPrice += parseFloat(value);
                    $("span.b_price").html(myCheckTotalPrice.toFixed(2))
                    $("span.b_count").html($("table :checkbox:gt(0):checked").length);
                })
            }else{
                $("span.b_price").html(0.0)
                $("span.b_count").html(0);
            }
        })

        //清空购物车
        $("#clearCart").click(function(){
            $.get("CartServlet","method=clearCart",function(msg){
                $("table").find("tr").remove();
                $("table").html("购物车空空的.快去买东西吧");
            });
        })

        //滚动事件.加载新数据
        $("#main").scroll(function () {
            // 判断滚动条是否到达底部
            //alert(this.scrollTop + this.clientHeight + " : "+ this.scrollHeight)
            if (this.scrollTop + this.clientHeight + 1 >= this.scrollHeight) {
                if(peipage.pageNo < peipage.pageTotal){
                    mypage("下一页");
                }
            }
        })

        //删除购物项
        $("table").find("a.peidelete").live("click" , function (){
            //所以我发异常请求给服务..把数据库中的数据删除掉
            var id = $(this).parents("tr").find("td").eq(1).html();
            var tr = $(this);
            $.get("CartServlet","method=deleteById&id="+id,function(msg){
                if(msg.code == 1){
                    //$(this) 直接使用这句代码.this的含义已经改变
                    tr.parents("tr").remove();//删除网页中的一行数据,但是数据库中的数据是没有删除的
                    layer.msg(msg.msg, {
                        icon: 1,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    });
                }else{
                    layer.msg(msg.msg, {
                        icon: 2,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    });
                }
            })
        })



    })

    function mypage(flag) {
        var pageNo = 1 ;
        if ("下一页" == flag) {
            pageNo = peipage.pageNo + 1;
        }

        $.post("CartServlet", "method=findCartByUid&pageNo="+pageNo, function (msg) {
            peipage = msg;
            for (let i = 0; i < msg.items.length; i++) {
                $("<tr>" +
                    "<td><input type='checkbox' value='"+msg.items[i].id+"'></td>" +
                    "<td>" + msg.items[i].id + "</td>" +
                    "<td>" + msg.items[i].name + "</td>" +
                    "<td class='peitd'><a style='text-decoration: none' href='javascript:void(0)'>+</a><span>" + msg.items[i].count + "</span><a style='text-decoration: none' href='javascript:void(0)'>-</a></td>" +
                    "<td>" + msg.items[i].price + "</td>" +
                    "<td>" + msg.items[i].totalPrice + "</td>" +
                    "<td><a class='peidelete' href='javascript:void(0)'>删除</a></td>" +
                    "</tr>").appendTo("table");
            }
        });
    }
</script>